package com.atguigu.gmall.cart.controller;


import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@Api(tags = "购物车管理")
@RestController
@RequestMapping("/api/cart")
public class CartApiController {


    @Autowired
    private CartService cartService;

    @ApiOperation("加入购物车")
    @RequestMapping("addToCart/{skuId}/{skuNum}")
    public Result addToCart(
            @PathVariable(name = "skuId") Long skuId,
            @PathVariable(name = "skuNum") Integer skuNum
    ) {
        CartInfo cartInfo = cartService.addToCart(skuId, skuNum);

        return Result.ok(cartInfo);
    }



    @ApiOperation("进入购物车中")
    @GetMapping("/cartList")
    public Result cartList(HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        String userTempId = AuthContextHolder.getUserTempId(request);
        List<CartInfo> cartInfoList = cartService.cartList(userId,userTempId);

        return Result.ok(cartInfoList);
    }

    @GetMapping("checkCart/{skuId}/{isChecked}")
    public Result checkCart(
            @PathVariable(name = "skuId") Long skuId,
            @PathVariable(name = "isChecked") Integer isChecked,
            HttpServletRequest request
    ){
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartService.checkCart(skuId,isChecked,userId);

        return Result.ok();
    }
    @DeleteMapping("deleteCart/{skuId}")
    public Result deleteCart(
            @PathVariable(name = "skuId") Long skuId,
            HttpServletRequest request
    ){
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartService.deleteCart(skuId,userId);
        return Result.ok();
    }

    //查询已经选中的购物车中商品
    @GetMapping("/getCartCheckedList/{userId}")
    public List<CartInfo> getCartCheckedList(@PathVariable(name = "userId") String userId){

        return cartService.getCartCheckedList(userId);
    }
}
